#!/usr/bin/env node

/**
 * 性能优化脚本
 * 分析和优化项目性能
 */

const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');

console.log('🚀 开始性能优化分析...\n');

// 1. 分析包大小
console.log('📦 分析包大小...');
try {
  // 检查是否有构建产物
  const distPath = path.join(__dirname, '../dist');
  if (fs.existsSync(distPath)) {
    const stats = getDirectorySize(distPath);
    console.log(`📊 构建产物大小: ${formatBytes(stats.size)}`);
    console.log(`📁 文件数量: ${stats.files}`);
  } else {
    console.log('💡 未找到构建产物，运行 npm run build 进行构建');
  }
} catch (error) {
  console.log('❌ 包大小分析失败:', error.message);
}

// 2. 分析依赖大小
console.log('\n📦 分析依赖大小...');
try {
  const packageJson = JSON.parse(fs.readFileSync(path.join(__dirname, '../package.json'), 'utf8'));
  const dependencies = packageJson.dependencies || {};
  const devDependencies = packageJson.devDependencies || {};
  
  console.log(`📊 生产依赖: ${Object.keys(dependencies).length} 个`);
  console.log(`🔧 开发依赖: ${Object.keys(devDependencies).length} 个`);
  
  // 检查大型依赖
  const largeDeps = [
    'electron',
    'vue',
    'element-plus',
    'lodash',
    'moment',
  ];
  
  const foundLargeDeps = largeDeps.filter(dep => 
    dependencies[dep] || devDependencies[dep],
  );
  
  if (foundLargeDeps.length > 0) {
    console.log('📈 大型依赖:');
    foundLargeDeps.forEach(dep => {
      console.log(`   - ${dep}`);
    });
  }
} catch (error) {
  console.log('❌ 依赖分析失败:', error.message);
}

// 3. 分析代码复杂度
console.log('\n🔍 分析代码复杂度...');
const srcDir = path.join(__dirname, '../src');
const codeStats = analyzeCodeComplexity(srcDir);

console.log('📊 代码统计:');
console.log(`   - 总文件数: ${codeStats.totalFiles}`);
console.log(`   - 总行数: ${codeStats.totalLines}`);
console.log(`   - 平均文件大小: ${Math.round(codeStats.totalLines / codeStats.totalFiles)} 行`);

if (codeStats.largeFiles.length > 0) {
  console.log('⚠️  大文件 (>500行):');
  codeStats.largeFiles.forEach(file => {
    console.log(`   - ${path.relative(process.cwd(), file.path)}: ${file.lines} 行`);
  });
}

// 4. 检查性能问题
console.log('\n🔍 检查性能问题...');
const performanceIssues = findPerformanceIssues(srcDir);

if (performanceIssues.length > 0) {
  console.log('⚠️  发现性能问题:');
  performanceIssues.forEach(issue => {
    console.log(`   - ${issue.type}: ${path.relative(process.cwd(), issue.file)}:${issue.line}`);
  });
} else {
  console.log('✅ 未发现明显性能问题');
}

// 5. 生成优化建议
console.log('\n💡 优化建议:');
const suggestions = generateOptimizationSuggestions(codeStats, performanceIssues);
suggestions.forEach(suggestion => {
  console.log(`   - ${suggestion}`);
});

// 6. 生成性能报告
const report = {
  timestamp: new Date().toISOString(),
  codeStats,
  performanceIssues: performanceIssues.length,
  suggestions,
};

fs.writeFileSync(
  path.join(__dirname, '../performance-report.json'),
  JSON.stringify(report, null, 2),
);

console.log('\n📊 性能报告已生成: performance-report.json');
console.log('🎉 性能分析完成！');

// 工具函数
function getDirectorySize(dirPath) {
  let size = 0;
  let files = 0;
  
  function traverse(currentPath) {
    const items = fs.readdirSync(currentPath);
    
    for (const item of items) {
      const itemPath = path.join(currentPath, item);
      const stat = fs.statSync(itemPath);
      
      if (stat.isDirectory()) {
        traverse(itemPath);
      } else {
        size += stat.size;
        files++;
      }
    }
  }
  
  traverse(dirPath);
  return { size, files };
}

function formatBytes(bytes) {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function analyzeCodeComplexity(dir) {
  const stats = {
    totalFiles: 0,
    totalLines: 0,
    largeFiles: [],
  };
  
  function traverse(currentPath) {
    const items = fs.readdirSync(currentPath);
    
    for (const item of items) {
      const itemPath = path.join(currentPath, item);
      const stat = fs.statSync(itemPath);
      
      if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
        traverse(itemPath);
      } else if (item.endsWith('.ts') || item.endsWith('.vue') || item.endsWith('.js')) {
        const content = fs.readFileSync(itemPath, 'utf8');
        const lines = content.split('\n').length;
        
        stats.totalFiles++;
        stats.totalLines += lines;
        
        if (lines > 500) {
          stats.largeFiles.push({ path: itemPath, lines });
        }
      }
    }
  }
  
  traverse(dir);
  return stats;
}

function findPerformanceIssues(dir) {
  const issues = [];
  
  function traverse(currentPath) {
    const items = fs.readdirSync(currentPath);
    
    for (const item of items) {
      const itemPath = path.join(currentPath, item);
      const stat = fs.statSync(itemPath);
      
      if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
        traverse(itemPath);
      } else if (item.endsWith('.ts') || item.endsWith('.vue') || item.endsWith('.js')) {
        const content = fs.readFileSync(itemPath, 'utf8');
        const lines = content.split('\n');
        
        lines.forEach((line, index) => {
          // 检查性能问题模式
          if (line.includes('document.querySelector') && !line.includes('//')) {
            issues.push({
              type: 'DOM查询',
              file: itemPath,
              line: index + 1,
              content: line.trim(),
            });
          }
          
          if (line.includes('setInterval') && !line.includes('//')) {
            issues.push({
              type: '定时器',
              file: itemPath,
              line: index + 1,
              content: line.trim(),
            });
          }
          
          if (line.includes('JSON.parse') && !line.includes('try') && !line.includes('//')) {
            issues.push({
              type: '未处理JSON解析',
              file: itemPath,
              line: index + 1,
              content: line.trim(),
            });
          }
        });
      }
    }
  }
  
  traverse(dir);
  return issues;
}

function generateOptimizationSuggestions(codeStats, performanceIssues) {
  const suggestions = [];
  
  if (codeStats.largeFiles.length > 0) {
    suggestions.push('考虑拆分大文件以提高可维护性');
  }
  
  if (performanceIssues.length > 0) {
    suggestions.push('修复发现的性能问题');
  }
  
  suggestions.push('启用代码分割和懒加载');
  suggestions.push('使用缓存系统减少重复计算');
  suggestions.push('优化图片和静态资源');
  suggestions.push('考虑使用 Web Workers 处理重计算');
  
  return suggestions;
}